import { ViewEventType } from '@app-nextmesh-env/nextmesh/types';
import { events } from '@app-nextmesh-env/nextmesh/utils';
import TabContext from '@mui/lab/TabContext';
import TabList from '@mui/lab/TabList';
import TabPanel from '@mui/lab/TabPanel';
import { Box } from '@mui/material';
import Tab from '@mui/material/Tab';
import { useEffect, useState } from 'react';
import { LogViewer } from './LogViewer';
import TableView from './TableView';

interface IShowTabs {
  show: boolean;
  tabs: string[];
}
const tabLabels = {
  table: '表格',
  log: '日志',
};
export default function BottomPanel() {
  const [value, setValue] = useState('');
  const [showTabs, setShowTabs] = useState<IShowTabs>({
    show: false,
    tabs: [],
  });
  useEffect(() => {
    events.on(
      ViewEventType.ShowBottomPanel,
      (show: boolean, tabs: string[] = []) => {
        setShowTabs({ show, tabs });
        if (tabs.length > 0) setValue(tabs[0]);
      },
    );
    return () => {
      events.off(ViewEventType.ShowBottomPanel);
    };
  });

  const handleChange = (_: React.SyntheticEvent, newValue: string) => {
    setValue(newValue);
  };

  if (!showTabs.show) return null;
  return (
    <div className='nm-appFrame__results'>
      <div className='nm-BottomPanelFrame'>
        <TabContext value={value}>
          <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
            <TabList onChange={handleChange}>
              {showTabs.tabs.map((tab) => (
                <Tab
                  label={tabLabels[tab]}
                  value={tab}
                />
              ))}
            </TabList>
          </Box>
          {showTabs.tabs.map((tab) => {
            let child = <></>;
            switch (tab) {
              case 'table':
                child = <TableView />;
                break;
              case 'log':
                child = <LogViewer />;
                break;
            }
            return (
              <TabPanel
                sx={{ padding: 0, maxHeight: '240px' }}
                value={tab}>
                {child}
              </TabPanel>
            );
          })}
        </TabContext>
      </div>
    </div>
  );
}
